import Logger from "./utils/Logger"
const He = new Logger("AB")
export default class AB {
  values: any
  constructor(e: any) {
    this.values = {}
    for (const t in e) {
      const i = e[t]
      if (i && i.ab)
        try {
          this.values[t] = Ge(i.ab)
        } catch (e) {
          He.warn(`Skipping key ${t}, could not pick: ${e}`)
        }
    }
  }
  get(e) {
    return this.values[e]
  }
  serialize() {
    return Object.keys(this.values).map(e => `${e}:${this.values[e]}`)
  }
}
function Ge(e) {
  if (0 === e.length) throw Error("A/B cannot choose from an empty choice array")
  let t = 0
  for (const i of e) {
    if (void 0 === i.value || void 0 === i.weight || i.weight < 0) throw Error(`Malformed AB choice: ${i}`)
    t += i.weight
  }
  const i = Math.random() * t
  let n = 0
  for (const t of e) if (((n += t.weight), i <= n)) return t.value
}
